<template>
        <div class="QilinUploadImage">
        <el-upload
            ref="uploadImageRef"
            :action="ownUploadImageConifg.action || '#' "
            :headers="ownUploadImageConifg.headers || {}"
            :list-type="ownUploadImageConifg.listType || 'picture-card' "
            :auto-upload="ownUploadImageConifg.autoUpload || false "
            :limit="ownUploadImageConifg.limit || 5 "
            :drag="ownUploadImageConifg.drag === false ? false : true "
            :file-list="ownUploadImageConifg.fileList || [] "
            :multiple="ownUploadImageConifg.multiple === false ? false : true "
            :disabled="ownUploadImageConifg.disabled || false"
            :show-file-list="true"
            :before-upload="handleBeforeUpload"
            :on-success="handleSuccess"
            :on-error="handleError"
            :on-change="handleChange"
            :on-preview="handlePreview"
            :on-remove="handleRemove"
            :on-exceed="handleExceed"
        >
            <div class="QilinUploadImage-iconImage">
                <div class="QilinUploadImage-iconImage-text flex-row">
                    <el-icon class="el-icon-upload"></el-icon>
                    <span>上传图片</span>
                </div>
                <div class="QilinUploadImage-iconImage-tip">
                    {{ownUploadImageConifg.fileSizeText || "大小20M以内"}}
                </div>
            </div>
        </el-upload>
        <span class="QilinUploadImage-tip">{{ownUploadImageConifg.fileTypeText || "(支持jpg、png、jpeg等图片格式)"}}</span>
        <QilinDialog :dialogConfig.sync="dialogConfig" @handleClose="closeDialog">
            <el-image
                style="width:100%;height:500px;"
                :src="currentImage"
                :preview-src-list="ownUploadImageConifg.fileList.map((item)=>{
                    return ownUploadImageConifg.action ? ownUploadImageConifg.imageIp || '' + item[ (ownUploadImageConifg.imageOptions && ownUploadImageConifg.imageOptions.serverUrl) || 'fileName'] : item.url;
                })"
                :initial-index="initialIndex"
                :fit="ownUploadImageConifg.imageFit || 'contain'"
            ></el-image>
        </QilinDialog>
    </div>
</template>

<script>
export default {
    name:"QilinUploadImage",
    props:{
        uploadImageConfig:{
            type:Object,
            default(){
                return {
                    action:"#", //文件上传至服务器url
                    headers:{}, //设置上传的请求头部--当action有值时必填，用以设置token等
                    listType:"picture-card", //文件列表类型
                    autoUpload:false, //是否自动上传，当action有值时，则autoUpload须为true
                    limit:5, //文件允许上传数量
                    fileList:[], //默认上传文件--必填
                    multiple:false, //是否支持多选文件
                    drag:true, //是否启用拖拽上传
                    disabled:false, //是否禁用上传
                    fileTypeText:"（支持png、jpg、jpeg、gif文件格式）", //支持格式文字说明
                    fileType:["png","jpg","jpeg","gif"], //支持上传的文件类型
                    fileSize:20 * 1000 * 1000, //文件上传大小限制20M之内默认
                    fileSizeText:"大小20M以内", //文件大小提示标语
                    imageFit:"contain", //图片的适应类型--默认contain
                    imageIp:"", //设置查看图片或文件的服务器ip--预览图片时须借助该属性或imageOptions属性的配置
                    imageOptions:{ //图片设置配置项
                        serverOriginalName:"originalFilename", //文件上传至后端，返回的原始文件名称
                        serverName:"newFileName", //文件上传至后端，返回的文件名称--用以回显文件的名称
                        serverUrl:"fileName", //文件上传至后端，返回的文件url地址--用以回显文件的url
                        serverWholeUrl:"url", //文件上传至后端，返回的完整的文件url地址--用以回显文件的完整url
                        responseDataName:"data", //文件上传至服务器，返回的响应字段，默认为data，通常也是data
                    }
                }
            }
        },
        fileList:{ //用以回显
            type:[Array,String],
            default(){
                return []
            }
        }
    },
    data(){
        return {
            currentImage:"", //当前预览图片url
            initialIndex:0, //当前预览图片索引位置
            dialogConfig:{ //图片预览弹窗配置项
                isShow:false,
                title:"图片预览",
                isHideFooter:true
            }
        }
    },
    computed:{
        ownUploadImageConifg:{
            get(){
                this.uploadImageConfig.fileList=this.fileList ? ( typeof this.fileList === "string" ? JSON.parse(this.fileList) : this.fileList || [] ) : [] ;
                return this.uploadImageConfig;
            },
            set(val){
                this.$emit("update:uploadImageConfig",val);
            }
        }
    },
    methods:{
        /**
         *  **当action为指定服务器地址时
         */
        // 文件上传之前的事件监听
        handleBeforeUpload(file){
            // console.log(file,this.ownUploadImageConifg.action);
            if(!this.ownUploadImageConifg.action || this.ownUploadImageConifg.action === "#") return ;
            const index=file.name.lastIndexOf(".");
            const fileType=file.name.slice(index+1).toLowerCase();
            if(this.ownUploadImageConifg.fileType && !this.ownUploadImageConifg.fileType.includes(fileType)){
                this.$message({
                    message:"请上传符合格式要求的图片",
                    type:"warning"
                });
                return false;
            }else if(!this.ownUploadImageConifg.fileType && !["png","jpg","jpeg","gif"].includes(fileType)){
                this.$message({
                    message:"请上传符合格式要求的图片",
                    type:"warning"
                });
                return false;
            }else if(file.size > (this.ownUploadImageConifg.fileSize || 20 * 1000 * 1000)){
                this.$message({
                    message:"文件大小超过限制",
                    type:"warning"
                });
                return false;
            };
        },
        // 文件上传成功后的事件监听
        handleSuccess(response,file,fileList){
            // console.log(response,file,fileList,"========");
            this.$emit("actionSuccess",response,file);
        },
        // 文件上传失败后的事件监听
        handleError(error,file,fileList){
            // console.log(error,file,fileList,"========");
            this.$message({
                message:"上传失败，请检查服务器",
                type:"error"
            });
        },

        /**
         *  **当action未填写时
         */
        // 文件上传状态改变事件监听
        handleChange(file){
            // console.log(file);
            if(this.ownUploadImageConifg.action) return ;
            const index=file.name.lastIndexOf(".");
            const fileType=file.name.slice(index+1).toLowerCase();
            if(this.ownUploadImageConifg.fileType && !this.ownUploadImageConifg.fileType.includes(fileType)){
                this.$message({
                    message:"请上传符合格式要求的图片",
                    type:"warning"
                });
                this.$nextTick(()=>{
                    this.$refs["uploadImageRef"].handleRemove(file);
                });
            }else if(!this.ownUploadImageConifg.fileType && !["png","jpg","jpeg","gif"].includes(fileType)){
                this.$message({
                    message:"请上传符合格式要求的图片",
                    type:"warning"
                });
                this.$nextTick(()=>{
                    this.$refs["uploadImageRef"].handleRemove(file);
                });
            }else if(file.size > (this.ownUploadImageConifg.fileSize || 20 * 1000 * 1000)){
                this.$message({
                    message:"文件大小超过限制",
                    type:"warning"
                });
                this.$nextTick(()=>{
                    this.$refs["uploadImageRef"].handleRemove(file);
                });
            }else{
                this.ownUploadImageConifg.fileList.push({
                    raw:file.raw,
                    url:file.url,
                    name:file.name
                });
                this.$emit("success",this.ownUploadImageConifg.fileList,file);
            };
        },
        // 文件超出限制事件监听
        handleExceed(file,files){
            // console.log(file,files);
            this.$message({
                message:"文件上传数量不能大于"+(this.ownUploadImageConifg.limit || 5)+"个",
                type:"warning"
            });
        },
        // 文件预览事件监听
        handlePreview(file){
            if(file.raw){ //若是本地上传后直接预览，亦有可能编辑回显预览（提交数据至后端时携带了raw字段或后端返回数据中含有raw字段）
                this.currentImage=file[(this.ownUploadImageConifg.imageOptions && this.ownUploadImageConifg.imageOptions.serverWholeUrl) || "url"];
                this.initialIndex=this.ownUploadImageConifg.fileList.findIndex((item)=>{
                    // return (item.raw && (item.raw.name === file.raw.name)) && (item.raw && (item.raw.uid === file.raw.uid));
                    return item.raw && (item.raw.name === file.raw.name && item.raw.uid === file.raw.uid)
                });
            }else{ //回显预览（提交数据至后端时未携带raw字段或祸后端返回数据中不含有raw字段）
                this.currentImage=file[(this.ownUploadImageConifg.imageOptions && this.ownUploadImageConifg.imageOptions.serverUrl) || "fileName"];
                this.initialIndex=this.ownUploadImageConifg.fileList.findIndex((item)=>{
                    return item[(this.ownUploadImageConifg.imageOptions && this.ownUploadImageConifg.imageOptions.serverUrl) || "fileName"] === this.currentImage;
                });
                this.currentImage=(this.ownUploadImageConifg.imageIp || "")+file[(this.ownUploadImageConifg.imageOptions && this.ownUploadImageConifg.imageOptions.serverUrl) || "fileName"];
            };
            this.dialogConfig.isShow=true;
        },
        // 文件删除事件监听
        handleRemove(file,files){
            // console.log(file,this.ownUploadImageConifg.fileList);
            let index=-1;
            if(file.raw){ //若是本地上传后直接删除
                if(!this.ownUploadImageConifg.action || this.ownUploadImageConifg.action === "#"){
                    index=this.ownUploadImageConifg.fileList.findIndex((item)=>{
                        return item.name === file.name && item.uid === file.uid;
                    });
                }else{ // 若是指定action上传方式
                    index=this.ownUploadImageConifg.fileList.findIndex((item)=>{
                        return item.raw && ((item.raw.name === file[(this.ownUploadImageConifg.imageOptions && this.ownUploadImageConifg.imageOptions.serverOriginalName) || "originalFilename"]) && (item.uid === file.uid));
                    });
                };
            }else{ //回显删除
                index=this.ownUploadImageConifg.fileList.findIndex((item)=>{
                    return item[(this.ownUploadImageConifg.imageOptions && this.ownUploadImageConifg.imageOptions.serverOriginalName) || "originalFilename"] === file[(this.ownUploadImageConifg.imageOptions && this.ownUploadImageConifg.imageOptions.serverOriginalName) || "originalFilename"];
                });
            };
            if(index !== -1){
                this.ownUploadImageConifg.fileList.splice(index,1);
                this.$emit("success",this.ownUploadImageConifg.fileList,index);
            };
        },
        // 关闭预览弹窗事件监听
        closeDialog(){
            this.dialogConfig.isShow=false;
        }
    },
    mounted(){

    }
}
</script>

<style lang="scss" scoped>
.QilinUploadImage{
    width:100%;
    >div:first-child{
        display:flex;
        flex-flow:row wrap;
        :deep(.el-upload-list--picture-card){
            .el-upload-list__item{
                width:80px;
                height:80px;
                .el-icon--close-tip{
                    display:none !important;
                }
            }
            // 解决自定义上传服务器时图片抖动问题
            .el-upload-list__item.is-ready,.el-upload-list__item.is-uploading {
                display: none !important;
            }
        }
        :deep(.el-upload){
            &.el-upload--picture-card{
                width:140px;
                height:80px;
                border:none;
                >.el-upload-dragger{
                    width:100%;
                    height:100%;
                    padding:15px;
                    border-color:$primary-text-color;
                    background-color:#FAFAFA;
                    >.QilinUploadImage-iconImage{
                        width:100%;
                        height:100%;
                        font-size:$small-text-size;
                        line-height:2;
                        >.QilinUploadImage-iconImage-text{
                            align-items:center;
                            justify-content: center;
                            >i{
                                font-size:$small-text-size;
                                margin:0;
                                line-height:1;
                            }
                            >span{
                                color:$common-text-color;
                                margin-left:5px;
                            }
                        }
                        >.QilinUploadImage-iconImage-tip{
                            color:$support-text-color;
                        }
                    }
                }
            }
        }
    }
    >.QilinUploadImage-tip{
        color:$support-text-color;
        font-size:$small-text-size;
        display:inline-block;
        margin-top:4px;
    }

}
</style>
